#include "threadPool.h"
#include "worker.h"
#include "cmdFunc.h"

// 数据库用户名密码
extern char *sqlName;
extern char *sqlPwd;

int tidArrInit(tidArr_t *ptidArr,int workerNum)//初始化子线程信息结构体
{
    ptidArr->arr = (pthread_t *)calloc(workerNum,sizeof(pthread_t));
    ptidArr->workerNum = workerNum;
    return 0;
}

int makeWorker(threadPool_t *pthreadPool)//创建工人进程
{
    for(int i = 0;i < pthreadPool->tidArr.workerNum;i++)
    {
        pthread_create(&pthreadPool->tidArr.arr[i],NULL,threadFunc,pthreadPool);
    }
    return 0;
}

void *threadFunc(void *arg)//子线程函数
{
    threadPool_t * pthreadPool = (threadPool_t *)arg;
    cwd_t cwd;
    bzero(&cwd,sizeof(cwd_t));
    pthread_mutex_lock(&pthreadPool->mutex);
    MYSQL* conn= mysql_init(NULL);
    MYSQL* cret = mysql_real_connect(conn,"localhost", sqlName, sqlPwd,"netdisk",0,NULL,0);
    if(NULL == cret)
    {
        printf("子线程数据库连接失败!\n");
        printf("%s\n",mysql_error(conn));
        exit(0);
    }

    pthread_mutex_unlock(&pthreadPool->mutex);
    while(1)
    {
        int netfd;
        cmd_t cmd;
        pthread_mutex_lock(&pthreadPool->mutex);
        while(pthreadPool->exitFlag == 0 && pthreadPool->taskQueue.queueSize <= 0)
        {
            pthread_cond_wait(&pthreadPool->cond,&pthreadPool->mutex);
        }
        if(pthreadPool->exitFlag == 1)
        {
            pthread_mutex_unlock(&pthreadPool->mutex);
            pthread_exit(NULL);
        }
        netfd = pthreadPool->taskQueue.pFront->netfd;
        deQueue(&pthreadPool->taskQueue);
        pthread_mutex_unlock(&pthreadPool->mutex);
        while(1){
            //接收cmd
            train_t train;
            int recvnRet = recvn(netfd,&train.length,sizeof(train.length));
            if(recvnRet == -1){
                //recvn报错,客户端断开连接
                break;
            }
            recvnRet = recvn(netfd,train.data,train.length);
            if(recvnRet == -1){
                //recvn报错,客户端断开连接
                break;
            }
            memcpy(&cmd,&train.data,sizeof(cmd_t)); 
            cmdServerHandler(conn,netfd, &cwd, &cmd);
            if(cmd.cmdToken[0] == 'q'){
                // quit
                break;
            }
        }
    }
    mysql_close(conn);
}
